"""Add follow_up_reminders table.

Revision ID: 20250118_add_follow_up_reminders
Revises: 20250117_add_intentions
Create Date: 2025-01-18 10:00:00.000000

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import sqlite


# revision identifiers, used by Alembic.
revision = '20250118_add_follow_up_reminders'
down_revision = '20250117_add_intentions'
branch_labels = None
depends_on = None


def upgrade() -> None:
    """Create follow_up_reminders table."""
    op.create_table(
        'follow_up_reminders',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('lead_id', sa.Integer(), nullable=False),
        sa.Column('visitor_sheet_id', sa.Integer(), nullable=True),
        sa.Column('reminder_type', sa.String(50), nullable=False),  # auto/manual
        sa.Column('trigger_reason', sa.String(200), nullable=True),  # 触发原因（如：看房3天未回访）
        sa.Column('reminder_time', sa.DateTime(), nullable=False),  # 提醒时间
        sa.Column('status', sa.String(20), nullable=False, server_default='pending'),  # pending/sent/completed/cancelled
        sa.Column('assigned_to', sa.Integer(), nullable=False),  # 分配给谁
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('sent_at', sa.DateTime(), nullable=True),  # 邮件发送时间
        sa.Column('completed_at', sa.DateTime(), nullable=True),  # 完成时间
        sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
        sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.text('CURRENT_TIMESTAMP')),
        sa.PrimaryKeyConstraint('id'),
        sa.ForeignKeyConstraint(['lead_id'], ['leads.id'], name='fk_follow_up_reminders_lead_id', ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['visitor_sheet_id'], ['visitor_sheets.id'], name='fk_follow_up_reminders_visitor_sheet_id', ondelete='SET NULL'),
        sa.ForeignKeyConstraint(['assigned_to'], ['users.id'], name='fk_follow_up_reminders_assigned_to', ondelete='CASCADE'),
    )

    # 创建索引以提升查询性能
    op.create_index('ix_follow_up_reminders_status', 'follow_up_reminders', ['status'])
    op.create_index('ix_follow_up_reminders_reminder_time', 'follow_up_reminders', ['reminder_time'])
    op.create_index('ix_follow_up_reminders_assigned_to', 'follow_up_reminders', ['assigned_to'])
    op.create_index('ix_follow_up_reminders_lead_id', 'follow_up_reminders', ['lead_id'])


def downgrade() -> None:
    """Drop follow_up_reminders table."""
    op.drop_index('ix_follow_up_reminders_lead_id', table_name='follow_up_reminders')
    op.drop_index('ix_follow_up_reminders_assigned_to', table_name='follow_up_reminders')
    op.drop_index('ix_follow_up_reminders_reminder_time', table_name='follow_up_reminders')
    op.drop_index('ix_follow_up_reminders_status', table_name='follow_up_reminders')
    op.drop_table('follow_up_reminders')
